package com.gitee.btssplib.parser

import com.gitee.btssplib.IDataParser
import java.nio.charset.StandardCharsets
import java.util.*

/**
 * @author John
 * @version 1.0
 */
class WeighDataParser : IDataParser<Double> {

    override fun clearCache() {
        byteCache?.clear()
    }

    companion object {
        const val SEPARATOR = 0x3D // 分隔符号"="
    }

    private var byteCache: ArrayList<Int>? = null // 字节缓存

    override fun parse(byte: Int): Double? {
        var cache = byteCache
        if (byte == SEPARATOR) {
            if (cache == null) {
                byteCache = ArrayList<Int>()
            } else {
                val buffer = ByteArray(cache.size)
                for (i in cache.indices) {
                    buffer[i] = cache[i].toByte()
                }
                var result: Double
                try {
                    result = String(buffer, StandardCharsets.US_ASCII).trim().reversed().toDouble()
                    result = Math.max(result, 0.0) // 结果不能少于0
                    return result
                } catch (e: Exception) {
                    e.printStackTrace()
                    return null
                } finally {
                    byteCache = ArrayList<Int>()
                }
            }
        } else {
            cache?.add(byte)
        }
        return null
    }
}